var express = require('express');
var uuidv1 = require('uuid/v1');
var bodyParser = require('body-parser');
var cookieParser = require('cookie-parser')
var cookieSession = require('cookie-session')
var multer = require('multer');

var upload = require('./server/upload');
var { save, getProject } = require('./server/dblink');
var getFile = require('./server/getFile');

var app = express();

app.set('view engine', 'ejs');
app.use(bodyParser.json());
app.use(cookieParser('Sd2i@Uozx6cjkl3w$e9C4'))
app.use(express.static(__dirname + '/dist'));
app.use(multer({ dest: './tmp' }).any());


app.use(cookieSession({
  name: 'JT',
  keys: [ 'K_68C2062804x0', 'K_528U60C8&202', 'K_We234id32%2' ],
  maxAge: 24 * 3600 * 1000
}))

// 上传
app.post('/upload', upload);
// 下载
app.use('/g/:fileName', getFile);
// 保存数据
app.post('/save', save);

// 用户查询
app.post('/getproject', getProject);


app.get('/p/:id', (req, res) => {
  res.render(__dirname + '/dist/share.ejs', {
    DATA: JSON.stringify({ ID: req.params.id })
  });
});

app.get('*', (req, res) => {
  console.log(req.session);

  var uuid = req.session.uuid || uuidv1();

  req.session.uuid = uuid;
  res.render(__dirname + '/dist/index.ejs', {
    DATA: JSON.stringify({
      UUID: uuid
    })
  });
});

app.use((err, req, res, next) => {
  console.error('ERROR: ', err)
  res.send(err.message || 'Something broke!')
});

app.listen(8081, function (error) {
  console.log('running 8081')
})
